import streamlit as st
import os
from PIL import Image
import glob
import base64
from io import BytesIO
from besins_selenium_downloaders.config import get_website_names
from besins_selenium_downloaders.file_manager import *
from besins_selenium_downloaders.streamlit_tools import configure_page_navigation


class ScreenshotsViewer:
    def __init__(self):
        self.setup_page_config()
        configure_page_navigation("screenshots_viewer")
        st.markdown(
            '<h1 class="common-title">📸 Screenshots Viewer</h1>',
            unsafe_allow_html=True,
        )
        self.main()

    def setup_page_config(self):
        st.set_page_config(
            page_title="Screenshots Viewer",
            page_icon="📸",
            layout="centered",
            initial_sidebar_state="expanded",
        )

        # Load and inject CSS
        common_css_path = os.path.join(os.path.dirname(__file__), "../css/common.css")
        with open(common_css_path) as f:
            st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

        css_path = os.path.join(os.path.dirname(__file__), "../css/screenshots_viewer.css")
        with open(css_path) as f:
            st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

    def main(self):
        # Get URL parameters
        query_params = st.query_params
        default_site = query_params.get("site", [None])
        default_date = query_params.get("date", [None])

        # Get the most recent folder as default
        date_folders = get_list_date_folders()
        if not date_folders:
            st.error("No date folders found in the current directory.")
            return
        date_folders.sort(reverse=True)

        # Set default folder based on URL parameter or most recent
        if default_date and default_date in date_folders:
            default_folder = default_date
            default_folder_index = date_folders.index(default_folder)
        else:
            default_folder = date_folders[0]
            default_folder_index = 0

        # Create two columns for the selectors
        col1, col2 = st.columns(2)

        with col1:
            # Folder selection with the URL parameter as default
            folder_path = st.selectbox(
                "📅 Select Date Folder",
                options=date_folders,
                index=default_folder_index,
                help="Choose the date folder to view screenshots",
            )

        if folder_path:
            # Check if the selected folder contains relevant files
            relevant_files = glob.glob(os.path.join(folder_path, "*.png")) + \
                             glob.glob(os.path.join(folder_path, "*.xlsx")) + \
                             glob.glob(os.path.join(folder_path, "*.xls"))
            
            if not relevant_files:  # Check if there are no relevant files
                st.warning("The selected folder is empty. Please select a folder with data.")
                return  # Exit the method if the folder is empty

            df = get_date_folder_analysis_as_dataframe(folder_path)
            sites = sorted(df["SiteName"].unique().tolist())

            if not sites:
                st.warning("No sites found in the selected folder.")
                return

            # Find the index of the default site
            if default_site and default_site in sites:
                default_site_index = sites.index(default_site)
            else:
                default_site_index = 0

            with col2:
                selected_site = st.selectbox(
                    "🌐 Select Site",
                    options=sites,
                    index=default_site_index,
                    help="Choose the site to view screenshots",
                )

            self.display_screenshots(folder_path, selected_site)

    def display_screenshots(self, folder_path, site_name):
        # Look for PNG files directly in the folder that start with the site name
        screenshots = []
        search_pattern = os.path.join(folder_path, "*.png")
        for file in glob.glob(search_pattern):
            filename = os.path.basename(file)
            if filename.startswith(site_name) and filename.endswith(".png"):
                screenshots.append(file)

        # Debug information
        st.markdown(
            f'<p class="centered-text">Found {len(screenshots)} screenshots for {site_name}</p>',
            unsafe_allow_html=True,
        )

        if not screenshots:
            st.markdown(
                f'<div class="no-screenshots">No screenshots found for {site_name} in this folder.</div>',
                unsafe_allow_html=True,
            )
            return

        # Sort screenshots by name
        screenshots.sort()

        # Create grid layout for screenshots
        st.markdown('<div class="screenshot-grid">', unsafe_allow_html=True)

        for screenshot in screenshots:
            filename = os.path.basename(screenshot)
            try:
                with open(screenshot, "rb") as img_file:
                    img_bytes = img_file.read()
                    encoded = base64.b64encode(img_bytes).decode()
                    img_base64 = f"data:image/png;base64,{encoded}"
            except Exception as e:
                st.error(f"Error reading image {filename}: {str(e)}")
                continue

            st.markdown(
                f"""
                <div class="screenshot-card">
                    <img src="{img_base64}" 
                        alt="{filename}">
                    <div class="screenshot-title">{filename}</div>
                </div>
                """,
                unsafe_allow_html=True
            )

        st.markdown('</div>', unsafe_allow_html=True)


if __name__ == "__main__":
    ScreenshotsViewer()
